void ClipPlane::init()
{
	ent = 0;
	Active(1);
	clipplaneslist.push_back(this);
}

ClipPlane::ClipPlane(Vector3D position, Vector3D normal)
{
	pos = position;
	nrm = normal;
	nrm.normalize();

	init();
}

ClipPlane::ClipPlane()
{
	init();
}

ClipPlane::~ClipPlane()
{
	clipplaneslist.remove(this);
}

void ClipPlane::Process()
{
	if(active)
	{
		if(ent!=0)
		{
			//debug::add(ent->GetName());

			float x = ent->X();
			float y = ent->Y();
			float z = ent->Z();

			float ax = ent->AX() * D2R;
			float ay = ent->AY() * D2R;
			float az = ent->AZ() * D2R;

			Vector3D norm(0,1,0);
			Matrix3D rot = Matrix3D::getRotateYawPitchRollMatrix(-ay,-ax,-az);
			
			norm = rot * norm;
			//norm.normalize();

			double v[4];
			v[0] = norm.x;
			v[1] = norm.y;
			v[2] = norm.z;

			v[3] = - (v[0]*x + v[1]*y + v[2]*z);

			
			ClipPlaneShare::plane[ClipPlaneShare::cnt][0] = (float)v[0];
			ClipPlaneShare::plane[ClipPlaneShare::cnt][1] = (float)v[1];
			ClipPlaneShare::plane[ClipPlaneShare::cnt][2] = (float)v[2];
			ClipPlaneShare::plane[ClipPlaneShare::cnt][3] = (float)v[3];
			
			glEnable(GL_CLIP_PLANE0 + ClipPlaneShare::cnt);
			glClipPlane(GL_CLIP_PLANE0 + ClipPlaneShare::cnt,v);

			ClipPlaneShare::cnt++;
			int a = 0;
		}
	}
}

void ProcessClipPlanes()
{
	TClipPlanesList::const_iterator ci = clipplaneslist.begin();
	TClipPlanesList::const_iterator ei = clipplaneslist.end();

	ClipPlaneShare::cnt = 0;
	for(;ci!=ei;++ci)
	{
		(*ci)->Process();
	}
}

void DisableAllClipPlanes()
{
	for(int i=0;i<ClipPlaneShare::cnt;++i)
	{
		glDisable(GL_CLIP_PLANE0 + i);
	}
}

void EnableAllClipPlanes()
{
	for(int i=0;i<ClipPlaneShare::cnt;++i)
	{
		glEnable(GL_CLIP_PLANE0 + i);
	}
}

void ClipPlane::BindEntity(Entity *ent_)
{
	ent = ent_;
}

void ClipPlane::Active(int active_)
{
	active = active_;
}